<template>
  <div>
    <div class="tag-box">
      <span class="title">{{ title }} :</span>
      <el-tag
        class="tag"
        v-for="item in modelValue"
        :key="item"
        @close="handleClose(item)"
        :closable="!disabled"
        effect="light"
        closable
        size="large"
      >
        {{ item }}
      </el-tag>
      <el-input
        v-if="inputVisible"
        ref="InputRef"
        v-model="inputValue"
        class="tag inp"
        size="large"
        :disabled="disabled"
        @keyup.enter="handleInputConfirm"
        @blur="handleInputConfirm"
      />
      <el-tag
        class="tag cancel"
        type="danger"
        v-if="inputVisible"
        @mousedown.prevent="cancel"
      >
        取消
      </el-tag>
      <el-button
        v-if="!inputVisible"
        class="tag"
        size="large"
        :disabled="disabled"
        @click="showInput"
      >
        + 新增规格属性
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  modelValue: {
    default: []
  },
  disabled: {
    default: false
  }
});

const emit = defineEmits({
  ["update:modelValue"](value) {
    return value;
  }
});

const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref(null);

const handleClose = (tag) => {
  const option = props.modelValue.filter((res) => {
    return res !== tag;
  });
  emit("update:modelValue", option);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value.length === 0) {
    inputVisible.value = false;
    return;
  }
  if (props.modelValue.indexOf(inputValue.value) !== -1) {
    ElMessage.error("规格属性已存在");
    return;
  }
  inputVisible.value = false;
  const option = [...props.modelValue, inputValue.value];
  emit("update:modelValue", option);
  inputValue.value = "";
};

const cancel = () => {
  InputRef.value.focus();
  inputValue.value = "";
  inputVisible.value = false;
};
</script>

<style lang="scss" scoped>
.tag-box {
  display: flex;
  align-items: center;
  padding: 5px 0;
  flex-wrap: wrap;
  .title {
    margin-right: 10px;
    font-size: 16px;
  }
  .tag {
    margin-right: 10px;
  }
  .inp {
    width: 60px;
  }
  .cancel {
    cursor: pointer;
    user-select: none;
  }
}
</style>
